<template>
  <div class="container">
   <el-card class="box-card">
    <!-- 标题 -->
    <template #header v-if="this.$route.query.id">
      <div class="card-header">
        <span>试题修改</span>
      </div>
    </template>
    <template #header v-else>
      <div class="card-header">
        <span>试题录入</span>
      </div>
    </template>
    <!-- 表单内容 -->
    <div class="content">
      <el-form :model="form" ref="FormRef" :rules="rules" label-position="right" label-width="120px" size="medium"
      @submit.prevent>

        <!-- 学科 -->
        <el-form-item label="学科：" prop="subjectID" class="required">
          <el-select v-model="form.subjectID" class="full-width-input" clearable @change="selectSubject">
            <el-option v-for="(item, index) in subjectIDOptions" :key="index" :label="item.label"
              :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

        <!-- 目录 -->
        <el-form-item label="目录：" prop="catalogID" class="required">
          <el-select v-model="form.catalogID" class="full-width-input" clearable>
            <el-option v-for="(item, index) in catalogIDOptions" :key="index" :label="item.directoryName"
              :value="item.id" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

        <!-- 企业 -->
        <el-form-item label="企业：" prop="enterpriseID" class="required">
          <el-select v-model="form.enterpriseID" class="full-width-input" clearable>
            <el-option v-for="(item, index) in enterpriseIDOptions" :key="index" :label="item.company"
                :value="item.id" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item prop="province" class="required" style="color: #606266;">
          <template #label>
            <div style="color: #606266;font-weight: 700;">城市：</div>
          </template>
              <el-select v-model="form.province" class="full-width-input" clearable style="width: 198px; margin-right: 4px;" @change="selectArea">
                <el-option v-for="(item, index) in provinceOptions" :key="index" :label="item"
                  :value="item" :disabled="item.disabled"></el-option>
              </el-select>
              <el-select v-model="form.city" class="full-width-input" clearable style="width: 198px;">
                <el-option v-for="(item, index) in cityOptions" :key="index" :label="item"
                  :value="item" :disabled="item.disabled"></el-option>
              </el-select>
        </el-form-item>

        <!-- 方向 -->
        <el-form-item label="方向：" prop="direction" class="required">
          <el-select v-model="form.direction" class="full-width-input" clearable>
            <el-option v-for="(item, index) in directionOptions" :key="index" :label="item"
              :value="item" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>

        <!-- 题型 -->
        <el-form-item label="题型：" prop="questionType" class="required">
          <el-radio-group v-model="form.questionType">
            <el-radio v-for="(item, index) in questionTypeOptions" :key="index" :label="item.value"
              style="{display: inline}">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 难度 -->
        <el-form-item label="难度：" prop="difficulty" class="required">
          <el-radio-group v-model="form.difficulty">
            <el-radio v-for="(item, index) in difficultyOptions" :key="index" :label="item.value"
               style="{display: inline}">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 题干 -->
        <el-form-item prop="question" class="required">
          <template #label>
            <div style="color: #606266;font-weight: 700;">题干：</div>
          </template>

          <quillEditor  style="width: 1130px;height: 200px;"  ref="myTextEditor" v-model:value="form.question" :options="editorOption" ></quillEditor>
        </el-form-item>

        <!-- 选项 -->
        <!-- <el-form-item  prop="options" class="required" style="margin-top: 70px;">
          <template #label>
            <div style="color: #606266;font-weight: 700;">选项：</div>
          </template>
              <el-radio-group v-model="radio">
                <el-radio :label="3">Option A</el-radio>
                <el-input>11</el-input>
                <el-radio :label="9">Option C</el-radio>
              </el-radio-group>
        </el-form-item> -->

        <!-- 单选 -->
        <el-form-item style="margin-top: 40px;" class="choiceClass" v-if="form.questionType !== '3'">
          <template #label>
            <div style="color: #606266;font-weight: 700;">选项：</div>
          </template>
         <template v-if="form.questionType === '1'">
            <el-row>
              <el-radio-group v-model="form.choiceRadio" @change="radioChoice" style="display: block;">
              <div style="display:flex;align-items: center;margin-bottom:50px" v-for="(item,index) in form.options" :key="index">
                <el-radio  :label="index">{{item.code+'：'}}</el-radio>
              <el-input style="width:250px;margin:0 20px" v-model="item.title" />

                    <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :before-upload="beforeUpload"
                      :show-file-list="false"
                      :http-request="onUpload"
                      :data="index"
                      >
                      <img v-if="item.img" :src="item.img" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon">
                      <span>上传图片</span>
                      </i>
                  </el-upload>

              </div>
              <el-button type="danger" :disabled="form.questionType!=='2'" @click="addOption" size="medium">+增加选项与答案</el-button
              >
              </el-radio-group>
            </el-row>
        </template>
        <!-- 多选框 -->
        <template v-if="form.questionType === '2'">
          <el-row>
              <el-checkbox-group v-model="form.checkList" @change="checkSelect">
                <div style="display:flex;align-items: center;margin-bottom:50px" v-for="(item,index) in form.options" :key="index">
                 <el-checkbox @change="checkboxChoice" :label="index">{{item.code + '：'}}</el-checkbox>
                <el-input style="width:250px;margin:0 20px" v-model="item.title"/>
                  <el-upload
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :before-upload="beforeUpload"
                      :show-file-list="false"
                      :http-request="onUploadcopy"
                      :data="index"
                      >
                      <img v-if="item.img" :src="item.img" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon">
                      <span>上传图片</span>
                      </i>
                  </el-upload>

              </div>
              <el-button type="danger" :disabled="form.questionType!=='2'" @click="addOption" size="medium">+增加选项与答案</el-button
              >
              </el-checkbox-group>
            </el-row>
        </template>
        </el-form-item>
         <!-- 解析视频 -->
        <el-form-item label="解析视频：" prop="videoURL" class="required">
          <el-input v-model="form.videoURL" clearable style="width:400px"></el-input>
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item prop="question" class="required">
          <template #label>
            <div style="color: #606266;font-weight: 700;">答案解析：</div>
          </template>
          <quillEditor style="width: 1130px;"  ref="myTextEditor" v-model:value="form.answer" :options="editorOption" @focus="onEditorFocus" @ready="onEditorReady($event)"></quillEditor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注：" prop="remarks" style="margin-top: 70px;">
          <el-input type="textarea" v-model="form.remarks" rows="3" style="width:400px"></el-input>
        </el-form-item>
        <!-- 试题标签 -->
         <!-- class="tagSelect" -->
        <el-form-item label="试题标签：" prop="tags"            >
          <!-- <el-select v-model="form.tags" class="full-width-input" clearable placeholder="请选择试题标签">
            <el-option v-for="(item, index) in tagsOptions" :key="index" :label="item.tagName"
              :value="item.id" :disabled="item.disabled"></el-option>
          </el-select> -->
 <!-- style="width: 400px;height: 100%;" -->
           <el-select v-model="form.tags"
            multiple
            placeholder="请选择试题标签"
            @blur="setTags"
           >
            <el-option
              v-for="item in tagsOptions"
              :key="item.id"
              :label="item.tagName"
              :value="item.tagName">
            </el-option>
          </el-select>

        </el-form-item>
        <!-- 底部按钮 -->
        <el-form-item>
          <el-button  type="primary" @click="submitForm" v-if="this.$route.query.id">确认修改</el-button>
          <el-button  type="success" @click="submitForm" v-else>确认提交</el-button>
        </el-form-item>
  </el-form>

    </div>

  </el-card>
  </div>
</template>

<script>

// 获取target值的方式，通过vue中的响应式对象可使用toRaw()方法获取原始对象
import { toRaw } from '@vue/reactivity'
// 引入富文本编辑器
// import { quillEditor } from '@vueup/vue-quill'
import { quillEditor } from 'vue3-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
// 引入city详情js
import { provinces, citys } from '@/api/hmmm/citys.js'
// 引入常量数据constans
import { direction, difficulty, questionType, array as checkListArray } from '../../api/hmmm/constants.js'
// 引入接口方法
import { simple, detail as detailSubject } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/companys'
import { list as directoryList } from '@/api/hmmm/directorys.js'
import { list as tagList } from '@/api/hmmm/tags.js'
import { add as addQuestion, detail, update } from '@/api/hmmm/questions.js'
// 初始化cos
// 与腾讯云cos对象存储建立链接
const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDCKI6nKguBnCSk6Skz74pNk2A8yd4KPde',
  SecretKey: 'rX2LURI1e9VhrtrgLqHAtW8dx88ynCIM'
})
export default {
  components: { quillEditor },
  props: {},
  data () {
    // 自定义校验
    const validcity = (rule, value, callback) => {
      if (!this.form.city) {
        callback(new Error('请选择地区'))
      } else {
        callback()
      }
    }
    return {
      // 富文本编辑器设置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote'], // 引用  代码块
            ['code-block', 'image', 'link'] // 链接、图片
          ]
        }
      },
      // 图片上传url
      imageUrl: '',
      fileList: [], // 文件列表
      // 表单数据

      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 省份
        city: '', // 城市
        direction: '', // 方向
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        choiceRadio: '', // 单选选项
        checkList: [], // 多选选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ], // 学科
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ], // 目录
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ], // 企业
        province: [
          { required: true, validator: validcity, trigger: 'change' }
        ], // 省份
        city: [
          { required: true, validator: validcity, trigger: 'change' }
        ], // 城市
        direction: [
          { required: true, message: '请选择方向', trigger: 'blur' }
        ], // 方向
        questionType: [
          { required: true, trigger: 'blur' }
        ], // 题型
        difficulty: [
          { required: true, trigger: 'blur' }
        ], // 难度
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ], // 题干
        answer: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ] // 答案解析
      },
      subjectIDOptions: [], // 学科列表
      catalogIDOptions: [], // 目录列表
      enterpriseIDOptions: [], // 企业列表
      provinceOptions: provinces(), // 城市列表
      cityOptions: [], // 区列表
      directionOptions: direction,
      questionTypeOptions: questionType,
      difficultyOptions: difficulty,
      tagsOptions: [] // 试题标签列表
    }
  },
  computed: {},
  watch: {

  },
  async created () {
    // 判断是否存在id
    if (this.$route.query.id) {
      const { data } = await detail(this.$route.query)
      console.log(data)
      // 修改isRight
      data.options.forEach(item => {
        if (item.isRight === 1) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      // 修改tags
      data.tags = data.tags.split(',')
      // 赋值给form 回显
      this.form = data
      // 寻找对应的isRight选项

      // for (let i = 0; i < this.form.options; i++) {

      // }
      // 单选回显
      if (this.form.questionType === '1') {
        const Radioindex = this.form.options.findIndex(item => {
          return item.isRight === true
        })
        this.form.choiceRadio = Radioindex
      }

      // 多选回显
      if (this.form.questionType === '2') {
        this.form.checkList = []
        const arr = this.form.options.map(item => {
          return item.isRight
        })
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] === true) {
            this.form.checkList.push(i)
          }
        }
        // Radioindex = this.form.options.findIndex(item => {
        //   return item.isRight === true
        // })

        // this.form.checkList.push(Radioindex)
      }
      //

      // console.log(citys())

      // 枚举 修改学科 目录名称
      // return
      // 渲染学科列表
      this.selectSubject(this.form.subjectID)
    }
    // 调用获取学科信息列表方法
    this.getSubject()
    // 调用获取企业列表方法
    this.getEnterprise()
    // 获取城市
    // console.log(provinces())
    // 获取目录信息
  },
  mounted () {
    // console.log(this.$refs.myTextEditor)
  },
  methods: {
    // 处理数据

    // 表单提交验证事件
    submitForm (FormRef) {
      this.$refs.FormRef.validate(async valid => {
        // if (!valid) return
        // TODO: 提交表单
        if (valid) {
          if (this.$route.query.id) {
            // 修改操作
            // 发送请求
            this.form.tags = this.form.tags.join(',')
            this.form.id = parseInt(this.$route.query.id)
            await update(this.form)
          } else {
            // 新增操作
            // 发送请求
            if (this.form.tags) {
              this.form.tags = this.form.tags.join(',')
            }
            await addQuestion(this.form)
          }
          // 提示成功
          this.$message.success('操作成功')
          // 刷新列表
          // 返回基础
          this.$router.push('/questions/list')
        } else {
          this.$message.error('添加失败')
        }
        // console.log(111)
      })
    },
    resetForm () {
      this.$refs.FormRef.resetFields()
    },
    // 上传时判断图片格式
    beforeUpload ({ type, size }) {
      // 判断图片类型
      if (!['image/png', 'image/jpg', 'image/jpeg', 'image/gif'].includes(type)) {
        this.$message.error('上传失败')
        return false
      }
      // 判断尺寸
      if (size > 5 * 1024 * 1024) {
        this.$message.error('图片尺寸过大')
        return false
      }
    },
    // 图片上传方法
    // 上传图片
    // 上传图片
    onUpload ({ data, file }) {
      console.log(data)
      const index = data
      // this.isShow = true
      cos.uploadFile({
        Bucket: 'rzzt-center-1258014218', // 桶名称
        Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + file.name, // 文件名
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          this.percent = progressData.percent * 100
        }
      }, async (err, data) => {
        this.isShow = false
        // 保证this指向，修改为箭头函数
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)

          // 上传成功后保存地址到data中的fileList
          this.fileList.push({ url: `http://${data.Location}` })
          // 通过字符串转换得到proxy中数据
          // const arr = JSON.parse(JSON.stringify(this.form.options))
          // await this.$nextTick()
          // const arr = toRaw(this.form.options)
          // console.log(arr[index])
          // arr[index].img = `http://${data.Location}`
          console.log('options', this.form.options, 'index', index)
          this.form.options[index].img = `http://${data.Location}`
        }
      })
    },
    onUploadcopy ({ data, file }) {
      console.log(data)
      const index = data
      // this.isShow = true
      cos.uploadFile({
        Bucket: 'rzzt-center-1258014218', // 桶名称
        Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + file.name, // 文件名
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          this.percent = progressData.percent * 100
        }
      }, async (err, data) => {
        this.isShow = false
        // 保证this指向，修改为箭头函数
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)

          // 上传成功后保存地址到data中的fileList
          // this.fileList.push({ url: `http://${data.Location}` })
          // 通过字符串转换得到proxy中数据
          // const arr = JSON.parse(JSON.stringify(this.form.options))
          // await this.$nextTick()
          // const arr = toRaw(this.form.options)
          // console.log(arr[index])
          // arr[index].img = `http://${data.Location}`
          console.log('options', this.form.options, 'index', index)
          this.form.options[index].img = `http://${data.Location}`
        }
      })
    },
    // 获取学科信息方法
    async getSubject () {
      const { data } = await simple()
      this.subjectIDOptions = data
    },
    // 获取企业详情方法
    async getEnterprise () {
      const { data } = await list({
        pagesize: 100
      })
      // console.log(data)
      this.enterpriseIDOptions = data.items
    },

    // 根据学科变化，获取目录列表和试题标签列表
    async selectSubject (val) {
      // console.log(val)
      // 发送请求获取目录列表
      const { data } = await directoryList({
        subjectID: val
      })
      this.catalogIDOptions = data.items
      // 发送请求获取试题标签列表
      const res = await tagList({
        subjectID: val
      })
      this.tagsOptions = res.data.items
    },
    // 根据城市选择，获取对应的区
    selectArea (val) {
      try {
        console.log(val)
        this.cityOptions = citys(val)
      } catch (error) {
        console.log(11)
      }
    },
    // 单选框选择
    radioChoice (val) {
      // await this.$nextTick()
      console.log(val)
      // 选中就让该选项的isRight变为true
      const arr = toRaw(this.form.options)
      console.log(arr[val])
      arr.forEach(el => {
        el.isRight = false
      })
      arr[val].isRight = true
    },

    // 多选框选择
    checkSelect (val) {
      const arr = toRaw(this.form.options)
      arr.forEach(el => {
        el.isRight = false
      })
      val.forEach(item => {
        arr[item].isRight = !arr[item].isRight
      })
    },
    // 增加多选框选项
    // 多选状态时添加多选选项
    addOption () {
      this.$nextTick(() => {
        this.form.options.push({
          isRight: false,
          code: checkListArray[this.form.options.length].code,
          title: '',
          img: ''
        })
      })
    },
    // 修改富文本框自动聚焦
    onEditorFocus (quill) {
      // console.log('editor focus!', quill)
      quill.enable(true)
    },
    // 修改富文本框自动聚焦
    onEditorReady (quill) {
      // console.log('editor ready!', quill)
      quill.enable(false)
    }

    // 设置tag数据
    // setTags () {
    //   setTimeout(() => {
    //     this.form.tags = this.form.tags.join(',')
    //   }, 0)
    // }
  }
}

</script>
<style lang="less">
// 头像上传样式
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    position: relative;

    span {
      font-size: 14px;
      color: #000;
      font-style: normal;
    }
  }
  .avatar {
    width: 100px;
    height: 50px;
    display: block;
  }
// .choiceBox {
//   margin-top: 50px;
// }
// 题干样式
// .el-form-item__content{
//   height: 200px;
// }
.ql-toolbar  {
  height: 40px;
}
// 单选框样式
.choiceClass .el-radio {
  margin-right: 0;
}
.container {
  padding: 20px;
}
.el-input__wrapper {
  width: 400px;
  height: 36px;
  padding: 0 15px;
}
.el-input-number.full-width-input,
  .el-cascader.full-width-input {
    width: 100% !important;
  }

  .el-form-item--medium {
    .el-radio {
      line-height: 36px !important;
    }

    .el-rate {
      margin-top: 8px;
    }
  }

  .el-form-item--small {
    .el-radio {
      line-height: 32px !important;
    }

    .el-rate {
      margin-top: 6px;
    }
  }

  .el-form-item--mini {
    .el-radio {
      line-height: 28px !important;
    }

    .el-rate {
      margin-top: 4px;
    }
  }

  .clear-fix:before,
  .clear-fix:after {
    display: table;
    content: "";
  }

  .clear-fix:after {
    clear: both;
  }

  .float-right {
    float: right;
  }
</style>
<style scoped lang="less">

.container {
  padding: 20px;
  :deep(.ql-toolbar) {
    width: 1130px;
  }
  :deep(.ql-editor) {
    width: 100%;
    height: 200px;
  }
  .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.content {
  padding: 20px;
}
}
div.table-container {
    table.table-layout {
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;

      td.table-cell {
        display: table-cell;
        height: 36px;
        border: 1px solid #e1e2e3;
      }
    }
  }

  div.tab-container {}

  .label-left-align :deep(.el-form-item__label) {
    text-align: left;
  }

  .label-center-align :deep(.el-form-item__label) {
    text-align: center;
  }

  .label-right-align :deep(.el-form-item__label) {
    text-align: right;
  }

  .custom-label {}

  .static-content-item {
    min-height: 20px;
    display: flex;
    align-items: center;

    :deep(.el-divider--horizontal) {
      margin: 0;
    }
  }

</style>
